<script setup lang="ts">
import { onMounted, ref } from "vue";
import Phaser from "phaser";
import { FindScene } from "./findScene";

defineProps<{ msg: string }>();
const title = ref("找茬游戏");
const findboxRef = ref();
let game: Phaser.Game;
let gameWidth = 0;
let gameHeight = 0;
let zoomRatio = 1;

function initGame() {
  // 先设置游戏尺寸
  gameWidth = findboxRef.value.clientWidth || 351;
  gameHeight = findboxRef.value.clientHeight || 542;
  gameHeight = gameHeight * window.devicePixelRatio;
  gameWidth = gameWidth * window.devicePixelRatio;
  zoomRatio = Number((gameHeight / 542).toFixed(4));

  const config: Phaser.Types.Core.GameConfig = {
    type: Phaser.AUTO,
    width: gameWidth,
    height: gameHeight,
    parent: findboxRef.value,
    canvasStyle: "width:100%;height:100%",
    backgroundColor: 0x291f61,
    scene: [
      new FindScene({ key: "FindScene" }, { zoomRatio, gameWidth, gameHeight }),
    ],
    render: {
      pixelArt: false,
      antialias: true,
      roundPixels: false,
      clearBeforeRender: true,
      failIfMajorPerformanceCaveat: false,
      powerPreference: "default",
    },
    scale: {
      mode: Phaser.Scale.RESIZE,
      parent: findboxRef.value,
      width: "100%",
      height: "100%",
      autoCenter: Phaser.Scale.CENTER_BOTH,
    },
  };

  game = new Phaser.Game(config);
}

onMounted(() => {
  // 确保DOM已经渲染完成
  setTimeout(() => {
    initGame();
  }, 100);
});
</script>

<template>
  <div class="container flex-center flex-col">
    <h1>{{ title }}</h1>
    <div ref="findboxRef" class="findbox"></div>
  </div>
</template>

<style scoped lang="less">
.findbox {
  width: 80%;
  height: 80%;
  position: relative;
  overflow: hidden;
  background-color: #291f61;
}
</style>